package com.example.demoexample.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.example.demoexample.R;

public class SlideButton extends LinearLayout {
    private int startLeft;
    private int startRight;
    private int startTop;
    private int startBottom;
    private int lastX;
    private int lastY;

    public SlideButton(Context context) {
        this(context, null);
    }

    public SlideButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("ClickableViewAccessibility")
    public SlideButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        View view = LayoutInflater.from(context).inflate(R.layout.layout_slide_button, this, true);
        ImageView ivTouch = view.findViewById(R.id.iv_touch);

        ivTouch.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                //获取手机触摸的坐标
                int x = (int) event.getX();
                int y = (int) event.getY();

                switch (action){
                    case MotionEvent.ACTION_DOWN://按下,获取小球初始的位置
                        startLeft = getLeft();
                        startRight = getRight();
                        startTop = getTop();
                        startBottom = getBottom();
                        lastX = x;
                        lastY = y;
                        break;
                    case MotionEvent.ACTION_MOVE://移动,小球跟随手指的移动
                        int offsetX = x - lastX;
                        int offsetY = y - lastY;
                        ivTouch.layout(getLeft()+offsetX,startTop,
                                getRight()+offsetX,startBottom);
                        break;
                    case MotionEvent.ACTION_UP://当手指抬起时,回到小球初始的位置
                        ivTouch.layout(startLeft, startTop, startRight, startBottom);
                        break;

                }

                return true;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }



    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

    }


}
